package com.avecsys.quotemanager.mbeans.buyer;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.icefaces.ace.component.dialog.Dialog;
import org.icefaces.ace.component.fileentry.FileEntryResults.FileInfo;
import org.icefaces.ace.json.JSONException;
import org.icefaces.ace.json.JSONObject;

import com.avecsys.quotemanager.constants.ApplicationConstants;
import com.avecsys.quotemanager.constants.BusinessCodes;
import com.avecsys.quotemanager.dao.common.EnumActor;
import com.avecsys.quotemanager.exception.BusinessException;
import com.avecsys.quotemanager.mbeans.core.BaseMBean;
import com.avecsys.quotemanager.pojos.BuyerUsersPojo;
import com.avecsys.quotemanager.pojos.QuoteTransactionEventsPojo;
import com.avecsys.quotemanager.pojos.QuoteTransactionPojo;
import com.avecsys.quotemanager.pojos.UserMasterPojo;
import com.avecsys.quotemanager.service.supplier.QuoteTransactionService;
import com.avecsys.quotemanager.ui.components.QuoteModifyDialog;
import com.avecsys.quotemanager.utils.MessageBoardUtil;
import com.avecsys.quotemanager.utils.TransactionStatus;
import com.avecsys.quotemanager.vo.BuyerVO;
import com.avecsys.quotemanager.vo.QuoteVO;
import com.icesoft.faces.component.ext.HtmlInputTextarea;

/**
 * @author Sam Sundar K
 */
public class QuoteEventReplyListMBean extends BaseMBean implements Serializable
{
	private final Log log = LogFactory.getLog(QuoteEventReplyListMBean.class);

	private QuoteTransactionService quoteTransactionService;

	private List<QuoteTransactionEventsPojo> quoteTransactionEventsPojoList = new ArrayList<QuoteTransactionEventsPojo>(
			0);

	private String buyerComments;

	private QuoteModifyDialog quoteModifyDialog = new QuoteModifyDialog("quoteModifyDialogID");

	private Dialog widgetQuoteModifyDialog;

	private HtmlInputTextarea widgetBuyerComments = new HtmlInputTextarea();

	/**
	 * @return the widgetBuyerComments
	 */
	public HtmlInputTextarea getWidgetBuyerComments()
	{
		return widgetBuyerComments;
	}

	/**
	 * @param widgetBuyerComments the widgetBuyerComments to set
	 */
	public void setWidgetBuyerComments(HtmlInputTextarea widgetBuyerComments)
	{
		this.widgetBuyerComments = widgetBuyerComments;
	}

	public void actionApproveOrAmendOrIgnoreQuote()
	{
		String requestJSON = getMessageDialog().getRequestJSON();
		JSONObject requestJSONObject;
		String eventId = null;
		String quoteActionType = null;
		String quoteName = null;
		try
		{
			requestJSONObject = new JSONObject(requestJSON);
			eventId = (String) requestJSONObject.get("eventId");
			quoteActionType = (String) requestJSONObject.get("quoteActionType");
			quoteName = (String) requestJSONObject.get("quoteName");
			QuoteTransactionEventsPojo quoteTransactionEventsPojo = quoteTransactionService.getQuoteTransactionEventById(new Long(
					eventId));
			if (quoteTransactionEventsPojo != null)
			{
				BuyerVO buyerVO = new BuyerVO();
				quoteTransactionEventsPojo.setTransactionStatus(quoteActionType);
				buyerVO.setQuoteTransactionEventsPojo(quoteTransactionEventsPojo);
				quoteTransactionEventsPojo.setBuyerComments(buyerComments);
				TransactionStatus transactionStatus = quoteTransactionService.replyQuoteEvent(buyerVO);
				loadAllPendingQuoteEventsForBuyer();
				MessageBoardUtil.publishTransactionStatusMessage(
						transactionStatus,
							EnumActor.SUPPLIER,
							"messageBoardId",
							"",
							new Object[]
							{ quoteName });
			}
			else
			{

			}
		}
		catch (BusinessException e)
		{
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
		catch (Exception e)
		{
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
		getMessageDialog().hideDialog();
	}

	public String actionBack()
	{
		return "openListSentQuotesToBuyer";
	}

	public String actionCreateModifyEvent()
	{
		String requestJSON = getQuoteModifyDialog().getRequestJSON();
		JSONObject requestJSONObject;
		String eventId = null;
		String quoteName = null;
		try
		{
			if (getQuoteModifyDialog().getComments() != null
					&& getQuoteModifyDialog().getComments().trim().length() > 0)
			{
				requestJSONObject = new JSONObject(requestJSON);
				eventId = (String) requestJSONObject.get("eventId");
				QuoteVO quoteVO = new QuoteVO();
				quoteVO.setEventId(Long.parseLong(eventId));
				quoteVO.setComments(getQuoteModifyDialog().getComments());
				quoteVO.setNewQuoteValue(getQuoteModifyDialog().getNewQuoteValue());
				FileInfo quoteAttachmentFileInfo = (FileInfo) FacesContext.getCurrentInstance()
						.getExternalContext()
						.getSessionMap()
						.get(ApplicationConstants.QUOTE_TRANSACTION_ATTACHEMNT_FILE_INFO);
				FacesContext.getCurrentInstance()
						.getExternalContext()
						.getSessionMap()
						.remove(ApplicationConstants.QUOTE_TRANSACTION_ATTACHEMNT_FILE_INFO);
				quoteVO.setQuoteAttachmentFileInfo(quoteAttachmentFileInfo);

				TransactionStatus transactionStatus = quoteTransactionService.createQuoteEvent(quoteVO);
				// TODO:
				loadQuoteEventHistoryForSupplier(quoteVO.getQuoteTransactionPojo());
				MessageBoardUtil.publishTransactionStatusMessage(
						transactionStatus,
							EnumActor.SUPPLIER,
							"messageBoardId",
							"",
							new Object[]
							{ quoteName });
				getQuoteModifyDialog().hideDialog();
			}
			else
			{
				getQuoteModifyDialog().showDialog();
				FacesContext.getCurrentInstance().validationFailed();
			}
		}
		catch (BusinessException e)
		{
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
		catch (Exception e)
		{
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
		return "openListSupplierQuoteEventHistory";
	}

	public void actionShowModifyQuoteDialog(ActionEvent actionEvent)
	{
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Map<String, String> paramValues = facesContext.getExternalContext().getRequestParameterMap();
		String eventId = (String) paramValues.get("eventId");
		String quoteName = (String) paramValues.get("quoteName");
		JSONObject requestJSONObject = new JSONObject();
		try
		{
			requestJSONObject.put("eventId", eventId);
			requestJSONObject.put("quoteName", quoteName);
			getQuoteModifyDialog().setRequestJSON(requestJSONObject.toString());
			getQuoteModifyDialog().showDialog();
		}
		catch (JSONException e)
		{
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
	}

	public void confirmQuoteAction(ActionEvent actionEvent)
	{
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Map<String, String> paramValues = facesContext.getExternalContext().getRequestParameterMap();
		String eventId = (String) paramValues.get("eventId");
		String quoteName = (String) paramValues.get("quoteName");
		String quoteActionType = (String) paramValues.get("QUOTE_ACTION_TYPE");
		JSONObject requestJSONObject = new JSONObject();
		try
		{
			requestJSONObject.put("eventId", eventId);
			requestJSONObject.put("quoteName", quoteName);
			requestJSONObject.put("quoteActionType", quoteActionType);
			getMessageDialog().setRequestJSON(requestJSONObject.toString());
			String quoteConfirmationType = "";
			if (BusinessCodes.QUOTE_EVENT_TRANSACTION_STATUS_BUYER_ACCEPT.equals(quoteActionType))
			{
				quoteConfirmationType = ApplicationConstants.ACTION_APPROVE_QUOTE_CONFIRMATION;
			}
			else if (BusinessCodes.QUOTE_EVENT_TRANSACTION_STATUS_BUYER_AMEND.equals(quoteActionType))
			{
				quoteConfirmationType = ApplicationConstants.ACTION_AMEND_QUOTE_CONFIRMATION;
			}
			else if (BusinessCodes.QUOTE_EVENT_TRANSACTION_STATUS_BUYER_IGNORE.equals(quoteActionType))
			{
				quoteConfirmationType = ApplicationConstants.ACTION_IGNORE_QUOTE_CONFIRMATION;
			}
			else
			{
				quoteConfirmationType = ApplicationConstants.ACTION_UNKNOWN_QUOTE_CONFIRMATION;
			}
			getMessageDialog().setMessage(
					MessageBoardUtil.getValue(
							facesContext,
								ApplicationConstants.RESOURCE_BUNDLE_SUPPLIER,
								quoteConfirmationType,
								new Object[]
								{ quoteName }));
		}
		catch (JSONException e)
		{
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
		getWidgetBuyerComments().setSubmittedValue("");
		getWidgetBuyerComments().setValue("");
		getMessageDialog().showDialog();
	}

	/**
	 * Method to decode the transaction status
	 * 
	 * @param transactionStatus
	 * @return decoded value
	 */
	public String decodeTransactionStatus(String transactionStatus)
	{
		return MessageBoardUtil.getValue(
				FacesContext.getCurrentInstance(),
					ApplicationConstants.RESOURCE_BUNDLE_COMMON,
					"QUOTE_EVENT_TRANSACTION_STATUS_" + transactionStatus,
					new Object[] {});
	}

	/**
	 * @return the buyerComments
	 */
	public String getBuyerComments()
	{
		return buyerComments;
	}

	/**
	 * @return the quoteModifyDialog
	 */
	public QuoteModifyDialog getQuoteModifyDialog()
	{
		return quoteModifyDialog;
	}

	/**
	 * @return the quoteTransactionEventsPojoList
	 */
	public List<QuoteTransactionEventsPojo> getQuoteTransactionEventsPojoList()
	{
		return quoteTransactionEventsPojoList;
	}

	/**
	 * @return the quoteTransactionService
	 */
	public QuoteTransactionService getQuoteTransactionService()
	{
		return quoteTransactionService;
	}

	/**
	 * @return the widgetQuoteModifyDialog
	 */
	public Dialog getWidgetQuoteModifyDialog()
	{
		return widgetQuoteModifyDialog;
	}

	public void loadAllPendingQuoteEventsForBuyer()
	{
		UserMasterPojo userMasterPojo = getSignedInUser();
		if (userMasterPojo != null)
		{
			for (BuyerUsersPojo buyerUsersPojo : userMasterPojo.getBuyerUsersPojo())
			{
				try
				{
					setQuoteTransactionEventsPojoList(quoteTransactionService.getAllQuoteTransactionEventsForBuyer(buyerUsersPojo.getBuyerMasterPojo()));
				}
				catch (BusinessException e)
				{
					log.error(e);
					MessageBoardUtil.publishException(e);
				}
			}
		}
	}

	/**
	 * @param quoteTransactionPojo
	 * @throws BusinessException
	 */
	public void loadQuoteEventHistoryForSupplier(QuoteTransactionPojo quoteTransactionPojo)
	{
		try
		{
			setQuoteTransactionEventsPojoList(quoteTransactionService.getAllQuoteTransactionEvents(quoteTransactionPojo));
		}
		catch (BusinessException e)
		{
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
	}

	/**
	 * @param buyerComments the buyerComments to set
	 */
	public void setBuyerComments(String buyerComments)
	{
		this.buyerComments = buyerComments;
	}

	/**
	 * @param quoteModifyDialog the quoteModifyDialog to set
	 */
	public void setQuoteModifyDialog(QuoteModifyDialog quoteModifyDialog)
	{
		this.quoteModifyDialog = quoteModifyDialog;
	}

	/**
	 * @param quoteTransactionEventsPojoList the quoteTransactionEventsPojoList to set
	 */
	public void setQuoteTransactionEventsPojoList(
			List<QuoteTransactionEventsPojo> quoteTransactionEventsPojoList)
	{
		this.quoteTransactionEventsPojoList = quoteTransactionEventsPojoList;
	}

	/**
	 * @param quoteTransactionService the quoteTransactionService to set
	 */
	public void setQuoteTransactionService(QuoteTransactionService quoteTransactionService)
	{
		this.quoteTransactionService = quoteTransactionService;
	}

	/**
	 * @param widgetQuoteModifyDialog the widgetQuoteModifyDialog to set
	 */
	public void setWidgetQuoteModifyDialog(Dialog widgetQuoteModifyDialog)
	{
		this.widgetQuoteModifyDialog = widgetQuoteModifyDialog;
	}

}
